import request from '@/utils/request';
import { requestWrapper, randomInt, randomDate, paginate } from '@/utils/mock';

// 获取流程定义列表
export function getProcessDefinitionList(params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/process/definition/list',
      method: 'get',
      params
    }),
    // 模拟数据
    () => {
      const pageNum = params?.pageNum || 1;
      const pageSize = params?.pageSize || 10;
      const total = 15; // 模拟总数
      
      // 流程类型
      const processTypes = ['请假流程', '报销流程', '采购流程', '出差流程', '会议室预订'];
      // 流程状态
      const statusOptions = ['0', '1']; // 0-停用 1-启用
      
      // 生成流程定义数据
      const generateProcessDefinition = (index) => {
        const processDefinitionId = index + 1;
        const processType = processTypes[randomInt(0, processTypes.length - 1)];
        const status = statusOptions[randomInt(0, statusOptions.length - 1)];
        const createTime = randomDate(-180);
        
        return {
          processDefinitionId,
          processKey: `process_${processType.replace(/流程|预订/g, '').toLowerCase()}`,
          processName: processType,
          version: randomInt(1, 5),
          category: '行政办公',
          status,
          deploymentId: `deploy_${processDefinitionId}`,
          resourceName: `${processType.replace(/流程|预订/g, '')}.bpmn`,
          diagramResourceName: `${processType.replace(/流程|预订/g, '')}.png`,
          description: `${processType}的流程定义`,
          createBy: 'admin',
          createTime,
          updateBy: randomInt(0, 1) ? 'admin' : null,
          updateTime: randomInt(0, 1) ? randomDate(-30) : null
        };
      };
      
      // 模拟分页
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = Math.min(startIndex + pageSize, total);
      const list = Array.from({ length: endIndex - startIndex }, (_, i) => generateProcessDefinition(startIndex + i));
      
      return paginate(list, pageNum, pageSize, total);
    }
  );
}

// 获取流程定义详情
export function getProcessDefinitionDetail(processDefinitionId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/workflow/process/definition/${processDefinitionId}`,
      method: 'get'
    }),
    // 模拟数据
    () => {
      const processTypes = ['请假流程', '报销流程', '采购流程', '出差流程', '会议室预订'];
      const processType = processTypes[randomInt(0, processTypes.length - 1)];
      
      return {
        processDefinitionId,
        processKey: `process_${processType.replace(/流程|预订/g, '').toLowerCase()}`,
        processName: processType,
        version: randomInt(1, 5),
        category: '行政办公',
        status: '1',
        deploymentId: `deploy_${processDefinitionId}`,
        resourceName: `${processType.replace(/流程|预订/g, '')}.bpmn`,
        diagramResourceName: `${processType.replace(/流程|预订/g, '')}.png`,
        description: `${processType}的流程定义`,
        formData: JSON.stringify({
          formItems: [
            { type: 'input', label: '标题', field: 'title', required: true },
            { type: 'textarea', label: '说明', field: 'description', required: false },
            { type: 'select', label: '紧急程度', field: 'priority', options: [{ label: '普通', value: '1' }, { label: '紧急', value: '2' }, { label: '非常紧急', value: '3' }], required: true }
          ]
        }),
        createBy: 'admin',
        createTime: randomDate(-180),
        updateBy: 'admin',
        updateTime: randomDate(-30)
      };
    }
  );
}

// 部署流程定义
export function deployProcessDefinition(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/process/definition/deploy',
      method: 'post',
      data,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }),
    // 模拟数据
    {
      processDefinitionId: randomInt(100, 999),
      processName: data.get('name') || '新流程',
      deploymentId: `deploy_${randomInt(100, 999)}`,
      message: '流程部署成功'
    }
  );
}

// 更新流程定义状态
export function updateProcessDefinitionStatus(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/process/definition/status',
      method: 'put',
      data
    }),
    // 模拟数据
    null
  );
}

// 删除流程定义
export function deleteProcessDefinition(deploymentId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/workflow/process/definition/${deploymentId}`,
      method: 'delete'
    }),
    // 模拟数据
    null
  );
}

// 获取流程实例列表
export function getProcessInstanceList(params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/process/instance/list',
      method: 'get',
      params
    }),
    // 模拟数据
    () => {
      const pageNum = params?.pageNum || 1;
      const pageSize = params?.pageSize || 10;
      const total = 30; // 模拟总数
      
      // 流程类型
      const processTypes = ['请假流程', '报销流程', '采购流程', '出差流程', '会议室预订'];
      // 流程状态
      const statusOptions = ['0', '1', '2', '3']; // 0-进行中 1-已完成 2-已取消 3-已拒绝
      
      // 生成流程实例数据
      const generateProcessInstance = (index) => {
        const processInstanceId = index + 1;
        const processType = processTypes[randomInt(0, processTypes.length - 1)];
        const status = statusOptions[randomInt(0, statusOptions.length - 1)];
        const startTime = randomDate(-60);
        let endTime = null;
        if (status !== '0') {
          const startDate = new Date(startTime);
          const endDate = new Date(startDate);
          endDate.setHours(endDate.getHours() + randomInt(1, 72));
          endTime = endDate.toISOString().replace('T', ' ').substring(0, 19);
        }
        
        return {
          processInstanceId,
          processDefinitionId: randomInt(1, 15),
          processDefinitionKey: `process_${processType.replace(/流程|预订/g, '').toLowerCase()}`,
          processDefinitionName: processType,
          businessKey: `BK${randomInt(10000, 99999)}`,
          title: `${processType}_${processInstanceId}`,
          status,
          startUserId: randomInt(1, 10),
          startUserName: `user${randomInt(1, 10)}`,
          startTime,
          endTime,
          duration: endTime ? Math.floor((new Date(endTime) - new Date(startTime)) / 1000) : null
        };
      };
      
      // 模拟分页
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = Math.min(startIndex + pageSize, total);
      const list = Array.from({ length: endIndex - startIndex }, (_, i) => generateProcessInstance(startIndex + i));
      
      return paginate(list, pageNum, pageSize, total);
    }
  );
}

// 获取流程实例详情
export function getProcessInstanceDetail(processInstanceId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/workflow/process/instance/${processInstanceId}`,
      method: 'get'
    }),
    // 模拟数据
    () => {
      const processTypes = ['请假流程', '报销流程', '采购流程', '出差流程', '会议室预订'];
      const processType = processTypes[randomInt(0, processTypes.length - 1)];
      const status = ['0', '1', '2', '3'][randomInt(0, 3)];
      const startTime = randomDate(-60);
      let endTime = null;
      if (status !== '0') {
        const startDate = new Date(startTime);
        const endDate = new Date(startDate);
        endDate.setHours(endDate.getHours() + randomInt(1, 72));
        endTime = endDate.toISOString().replace('T', ' ').substring(0, 19);
      }
      
      return {
        processInstanceId,
        processDefinitionId: randomInt(1, 15),
        processDefinitionKey: `process_${processType.replace(/流程|预订/g, '').toLowerCase()}`,
        processDefinitionName: processType,
        businessKey: `BK${randomInt(10000, 99999)}`,
        title: `${processType}_${processInstanceId}`,
        status,
        startUserId: randomInt(1, 10),
        startUserName: `user${randomInt(1, 10)}`,
        startTime,
        endTime,
        duration: endTime ? Math.floor((new Date(endTime) - new Date(startTime)) / 1000) : null,
        variables: {
          title: `${processType}_${processInstanceId}`,
          description: `这是一个${processType}申请`,
          priority: randomInt(1, 3).toString(),
          days: randomInt(1, 10),
          amount: randomInt(100, 10000)
        },
        tasks: [
          {
            taskId: `task_${processInstanceId}_1`,
            taskName: '提交申请',
            assignee: `user${randomInt(1, 10)}`,
            startTime: startTime,
            endTime: startTime,
            status: '1' // 已完成
          },
          {
            taskId: `task_${processInstanceId}_2`,
            taskName: '部门经理审批',
            assignee: `user${randomInt(1, 10)}`,
            startTime: startTime,
            endTime: status !== '0' ? endTime : null,
            status: status !== '0' ? '1' : '0' // 0-进行中 1-已完成
          }
        ]
      };
    }
  );
}

// 取消流程实例
export function cancelProcessInstance(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/process/instance/cancel',
      method: 'post',
      data
    }),
    // 模拟数据
    {
      message: '流程已取消'
    }
  );
}

// 获取我的待办任务
export function getMyTodoTasks(params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/task/todo',
      method: 'get',
      params
    }),
    // 模拟数据
    () => {
      const pageNum = params?.pageNum || 1;
      const pageSize = params?.pageSize || 10;
      const total = 12; // 模拟总数
      
      // 流程类型
      const processTypes = ['请假流程', '报销流程', '采购流程', '出差流程', '会议室预订'];
      
      // 生成待办任务数据
      const generateTodoTask = (index) => {
        const taskId = index + 1;
        const processType = processTypes[randomInt(0, processTypes.length - 1)];
        const createTime = randomDate(-30);
        
        return {
          taskId,
          taskName: '部门经理审批',
          processInstanceId: randomInt(1, 100),
          processDefinitionId: randomInt(1, 15),
          processDefinitionName: processType,
          title: `${processType}_${randomInt(1, 100)}`,
          priority: randomInt(1, 3).toString(),
          createTime,
          dueTime: null,
          assignee: 'currentUser'
        };
      };
      
      // 模拟分页
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = Math.min(startIndex + pageSize, total);
      const list = Array.from({ length: endIndex - startIndex }, (_, i) => generateTodoTask(startIndex + i));
      
      return paginate(list, pageNum, pageSize, total);
    }
  );
}

// 获取我的已办任务
export function getMyDoneTasks(params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/task/done',
      method: 'get',
      params
    }),
    // 模拟数据
    () => {
      const pageNum = params?.pageNum || 1;
      const pageSize = params?.pageSize || 10;
      const total = 20; // 模拟总数
      
      // 流程类型
      const processTypes = ['请假流程', '报销流程', '采购流程', '出差流程', '会议室预订'];
      // 任务结果
      const resultOptions = ['通过', '驳回', '转办'];
      
      // 生成已办任务数据
      const generateDoneTask = (index) => {
        const taskId = index + 1;
        const processType = processTypes[randomInt(0, processTypes.length - 1)];
        const createTime = randomDate(-60);
        const completeTime = randomDate(-30);
        
        return {
          taskId,
          taskName: '部门经理审批',
          processInstanceId: randomInt(1, 100),
          processDefinitionId: randomInt(1, 15),
          processDefinitionName: processType,
          title: `${processType}_${randomInt(1, 100)}`,
          priority: randomInt(1, 3).toString(),
          createTime,
          completeTime,
          duration: Math.floor((new Date(completeTime) - new Date(createTime)) / 1000),
          assignee: 'currentUser',
          result: resultOptions[randomInt(0, resultOptions.length - 1)],
          comment: '同意'
        };
      };
      
      // 模拟分页
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = Math.min(startIndex + pageSize, total);
      const list = Array.from({ length: endIndex - startIndex }, (_, i) => generateDoneTask(startIndex + i));
      
      return paginate(list, pageNum, pageSize, total);
    }
  );
}

// 获取我发起的流程
export function getMyProcesses(params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/process/my',
      method: 'get',
      params
    }),
    // 模拟数据
    () => {
      const pageNum = params?.pageNum || 1;
      const pageSize = params?.pageSize || 10;
      const total = 15; // 模拟总数
      
      // 流程类型
      const processTypes = ['请假流程', '报销流程', '采购流程', '出差流程', '会议室预订'];
      // 流程状态
      const statusOptions = ['0', '1', '2', '3']; // 0-进行中 1-已完成 2-已取消 3-已拒绝
      
      // 生成我的流程数据
      const generateMyProcess = (index) => {
        const processInstanceId = index + 1;
        const processType = processTypes[randomInt(0, processTypes.length - 1)];
        const status = statusOptions[randomInt(0, statusOptions.length - 1)];
        const startTime = randomDate(-90);
        let endTime = null;
        if (status !== '0') {
          const startDate = new Date(startTime);
          const endDate = new Date(startDate);
          endDate.setHours(endDate.getHours() + randomInt(1, 72));
          endTime = endDate.toISOString().replace('T', ' ').substring(0, 19);
        }
        
        return {
          processInstanceId,
          processDefinitionId: randomInt(1, 15),
          processDefinitionName: processType,
          title: `${processType}_${processInstanceId}`,
          status,
          currentTask: status === '0' ? '部门经理审批' : null,
          currentAssignee: status === '0' ? `user${randomInt(1, 10)}` : null,
          startTime,
          endTime,
          duration: endTime ? Math.floor((new Date(endTime) - new Date(startTime)) / 1000) : null
        };
      };
      
      // 模拟分页
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = Math.min(startIndex + pageSize, total);
      const list = Array.from({ length: endIndex - startIndex }, (_, i) => generateMyProcess(startIndex + i));
      
      return paginate(list, pageNum, pageSize, total);
    }
  );
}

// 完成任务
export function completeTask(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/task/complete',
      method: 'post',
      data
    }),
    // 模拟数据
    {
      message: '任务已完成'
    }
  );
}

// 转办任务
export function delegateTask(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/task/delegate',
      method: 'post',
      data
    }),
    // 模拟数据
    {
      message: '任务已转办'
    }
  );
}

// 获取流程图
export function getProcessDiagram(processInstanceId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/workflow/process/diagram/${processInstanceId}`,
      method: 'get',
      responseType: 'blob'
    }),
    // 模拟数据
    () => new Blob(['模拟流程图数据'], { type: 'image/png' })
  );
}

// 启动流程
export function startProcess(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/workflow/process/start',
      method: 'post',
      data
    }),
    // 模拟数据
    {
      processInstanceId: randomInt(100, 999),
      message: '流程已启动'
    }
  );
} 